<template>
  <div class="can-container">
    <div>
      <span class="title">角色查询</span>
      <el-divider></el-divider>
      <div class="form filter-container">
        <el-form :model="searchForm" label-width="100px" label-position="left">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.name" style="width:224px"></el-input>
          </el-form-item>
        </el-form>
        <div style="margin-left: 100px;">
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <!-- <el-button icon="el-icon-refresh" @click="handleReset('queryForm')">重置</el-button> -->
        </div>
      </div>
    </div>
    <div class="userList">
      <span class="title">角色列表</span>
      <!-- <el-divider></el-divider>
      <div class>
        <el-button icon="el-icon-plus" type="primary" @click="handleNewAddRole">新增</el-button>
        <el-button icon="el-icon-delete" type="danger" :disabled="multipleSelection.length == 0" @click="handleBatchDelete">删除所选</el-button>
      </div> -->
      <el-divider></el-divider>
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" v-loading="isRoleLoading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="code" label="角色代码" align="center"></el-table-column>
        <el-table-column prop="description" label="角色描述" align="center"></el-table-column>

        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="primary" @click="handleEditeRole(scope.row)">编辑</el-button> -->
            <el-button size="mini" type="primary" @click="handlePermisson(scope.row)">权限</el-button>
            <el-button size="mini" type="primary" @click="handleProcess(scope.row)">流程控制</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDeleteRole(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="10" layout="prev, pager, next, jumper" :total="roleTotal"></el-pagination>
      </div>
    </div>

    <!-- 添加、编辑角色 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="rolesDialog" width="20%" center @close="handleClose">
      <div style="border-top:1px solid #E9E9E9;margin-bottom:30px;"></div>
      <div>
        <el-form :model="editForm" label-width="80px" ref="roleForm">
          <el-form-item label="角色名称" prop="name" :rules="[{required:true,message:'非空！'}]">
            <el-input v-model="editForm.name" placeholder="请输入角色名称" style="width:244px"></el-input>
          </el-form-item>
          <!-- <el-form-item label="角色代码">
            <el-input v-model="editForm.roleCode" style="width:224px"></el-input>
          </el-form-item>-->
          <el-form-item label="所属机构" prop="organizationId" :rules="[{required:true,message:'非空！'}]">
            <el-select v-model="editForm.organizationId" filterable placeholder="请输入所属机构" style="width:244px">
              <el-option v-for="item in organizationData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input type="textarea" v-model="editForm.description" style="width:244px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('roleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色权限设置 -->
    <el-dialog :close-on-click-modal="false" title="角色权限设置" :visible.sync="setLimitDialog" width="50%" center @close="handleClosePermission">
      <div style="border-top:1px solid #E9E9E9;margin-bottom:30px;"></div>
      <div>
        <div class="authorization">
          <span>
            授权角色：
            <span class="authorizationRoles">{{permissonData.name}}</span>
          </span>
        </div>
      </div>
      <!-- 权限树形列表 -->
      <div class="permissonList setScroll" v-loading="setLimitDialogLoading">
        <el-tree :data="menuData" :props="defaultProps" default-expand-all ref="tree" node-key="id" show-checkbox @check="nodeClick" :default-checked-keys="menuRoleData">
          <span class="custom-tree-node" slot-scope="{ node }">
            <span>{{ node.label}}</span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setLimitDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitPermission" :loading="permissionBtnLoading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 流程控制弹框 -->
    <el-dialog :close-on-click-modal="false" title="流程控制设置"  :visible.sync="processDialog.visible" width="50%" center @close="handleClosePermission">
      <div style="border-top:1px solid #E9E9E9;margin-bottom:30px;"></div>
      <div class="authorization">
        <span>
          授权角色：
          <span class="authorizationRoles">{{permissonData.name}}</span>
        </span>
        <el-select size="mini" style="float:right" v-model="processDialog.type" @change="handleChangeProcess">
          <el-option :value="0" label="农村建设用地复垦"></el-option>
          <el-option :value="1" label="国土综合整治"></el-option>
        </el-select>
        <div style="clear:both"></div>
      </div>
      <div class="processList setScroll" v-loading="processDialog.loading">
        <el-tree :data="processDialog.list" :props="defaultProps" default-expand-all ref="tree" node-key="key" show-checkbox @check="handleClickNodeProcess" :default-checked-keys="processDialog.checkedKeys">
          <span class="custom-tree-node" slot-scope="{ node }">
            <span>{{ node.label}}</span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="processDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitProcess" :loading="processDialog.btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getRoleTable, 
  getOrganizationData, 
  roleNewAdd, 
  roleEdite, 
  roleDelete, 
  getMenuData, 
  rolePermissonById, 
  saveRolePermisson, 
  getRoleDetail,
  getAllProcessData,
  saveRoleProcessData,
  getRoleProcessData
 } from "@/api/project/system/role.js";
export default {
  data() {
    return {
      //查询条件
      searchForm: {
        name: ""
        // roleCode:''
      },
      //表格
      isRoleLoading: false,
      tableData: [],
      multipleSelection: [],
      //分页
      currentPage: 1,
      roleTotal: 0,
      //角色新建、编辑
      rolesDialog: false, //角色弹框
      title: "",
      editForm: {
        name: "",
        // roleCode:'',
        organizationId: "",
        description: ""
      },
      //授权菜单
      setLimitDialog: false, //角色权限弹框
      setLimitDialogLoading:false,
      //获取所有机构数据
      organizationData: [],
      //角色新增、编辑
      submitType: 0, //0:新增；1:编辑
      //获取所有菜单数据
      menuData: [],
      //角色拥有菜单权限
      menuRoleData: [],
      permissonData: {},
      defaultProps: {
        label: "name"
      },
      //权限已勾选列表
      checkedNode: [],
      //权限提交按钮动画
      permissionBtnLoading: false,
      isStrictly: false, //树结构是否关联
      //流程控制
      processDialog:{
        visible:false,
        loading:false,
        btnLoading:false,
        type:0,
        list:[],
        checkedKeys:[],
        checkedKeysData:[]
      },
      processAllData:{},
      processRoleData:{},
    };
  },
  created() {
    this.getInitData();
  },
  methods: {
    //初始化数据
    getInitData: function() {
      this.handleGetTableData();
      this.handleGetOrganization();
      this.handleGetMenuData();
      this.bindGetAllProcess();
    },
    //获取角色列表数据
    handleGetTableData: function(page) {
      this.isRoleLoading = true;
      page ? (this.currentPage = page) : "";
      let params = {
        page: this.currentPage,
        size: 10
      };
      params = Object.assign(params, this.searchForm);
      getRoleTable(params).then(res => {
        this.roleTotal = res.data.total;
        this.tableData = res.data.rows.filter(item => {
          return item.name != '超级管理员'
        });
        this.isRoleLoading = false;
      });
    },
    //获取所有机构数据
    handleGetOrganization: function() {
      let params = {
        page: 1,
        size: 9999
      };
      getOrganizationData(params).then(res => {
        this.organizationData = res.data.rows;
      });
    },
    //获取所有菜单列表数据
    handleGetMenuData: function() {
      getMenuData().then(res => {
        //返回数据处理
        let data = res.data;
        this.menuData = this.menuHandle(data);
      });
    },
    //菜单数据处理
    menuHandle: function(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach(item => {
        delete item.children;
      });
      let map = {};
      data.forEach(item => {
        map[item.id] = item;
      });
      data.forEach(item => {
        let parent = map[item.parentId];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    //条件查询
    handleSearch: function() {
      this.handleGetTableData(1);
    },
    //新增弹框
    handleNewAddRole: function() {
      this.rolesDialog = true;
      this.submitType = 0;
      this.title = "新增角色";
    },
    //新增、编辑提交按钮
    handleSubmit: function(formName) {
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = that.editForm;
          if (this.submitType == 0) {
            roleNewAdd(params).then(res => {
              this.$message.success("操作成功！");
              this.rolesDialog = false;
              this.handleGetTableData(1);
            });
          } else {
            roleEdite(params).then(res => {
              this.$message.success("操作成功！");
              this.rolesDialog = false;
              this.handleGetTableData();
            });
          }
        }
      });
    },
    //弹框关闭回调
    handleClose: function() {
      this.editForm = {
        name: "",
        organizationId: "",
        description: ""
      };
      this.$refs["roleForm"].resetFields();
    },
    //角色赋权关闭回调
    handleClosePermission: function() {
      this.$refs.tree.setCheckedKeys([]);
    },
    //批量删除
    handleBatchDelete: function() {
      let roles = this.multipleSelection;
      this.$confirm("此操作将永久删除所选角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(res => {
        let ids = this.multipleSelection
          .map(item => {
            return item.id;
          })
          .join(",");
        let params = {
          ids: ids
        };
        roleDelete(params).then(res => {
          this.$message.success("操作成功！");
          this.handleGetTableData(1);
        });
      });
    },
    //编辑
    handleEditeRole: function(row) {
      this.title = "编辑角色";
      this.submitType = 1;
      let datas = Object.assign({}, row);
      datas["organizationId"] = datas.organization.id;
      this.editForm = datas;
      this.rolesDialog = true;
    },
    //权限赋予
    handlePermisson: function(row) {
      this.setLimitDialog = true;
      this.permissonData = row;
      this.getRolePermisson(row.id);
    },
    //根据角色获取权限菜单
    getRolePermisson: function(id) {
      let params = {
        roleId: id
      };
      this.setLimitDialogLoading = true;
      rolePermissonById(params).then(res => {
        this.menuRoleData = [];
        let menuData = this.menuHandle(res.data);
        this.handelMenuOption(menuData);
        this.setLimitDialogLoading = false;
      });
    },
    handelMenuOption: function(data) {
      data.forEach(item => {
        if ("children" in item) {
          this.handelMenuOption(item.children);
        } else {
          this.menuRoleData.push(item.id);
        }
      });
    },
    //点击权限回调
    nodeClick: function(a, b) {
      let checkedNode = b.checkedNodes.concat(b.halfCheckedNodes);
      this.checkedNode = checkedNode;
    },
    //权限确定、
    submitPermission: function() {
      let checkedNodes = JSON.parse(JSON.stringify(this.checkedNode));
      checkedNodes = checkedNodes.map(item => {
        delete item["children"];
        return item.id;
      });
      let params = {
        roleId: this.permissonData.id,
        menuIdList: checkedNodes
      };
      this.permissionBtnLoading = true;
      saveRolePermisson(params).then(res => {
        this.$message.success("操作成功！");
        this.permissionBtnLoading = false;
        this.setLimitDialog = false;
      });
    },
    //单个删除
    handleDeleteRole: function(row) {
      this.$confirm("此操作将永久删除此角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(res => {
        let params = {
          ids: row.id
        };
        roleDelete(params).then(res => {
          this.$message.success("操作成功！");
          this.handleGetTableData(1);
        });
      });
    },
    //流程控制弹框
    handleProcess:function (row) {
      this.processDialog.visible = true;
      this.permissonData = row;
      this.handleGetHasProcess(row.id);
    },
    //获取所有类型/所有流程
    bindGetAllProcess:function () {
      getAllProcessData().then(res => {
        if(res.data){
          this.processAllData = res.data;
          this.processDialog['list'] = res.data.showReclaimFlow;
        }
      })
    },
    //获取当前角色拥有流程权限
    handleGetHasProcess:function (id) {
      let params = {
        roleId : id
      };
      getRoleProcessData(params).then(res => {
        this.processRoleData = res.data;
        // 默认展示        
        if(this.processDialog.type == 0){
          this.processDialog['checkedKeys'] = this.processRoleData.reclaimFlow.map(item => {
            return item.key
          });
        }else{
          this.processDialog['checkedKeys'] = this.processRoleData.renovationFlow.map(item => {
            return item.key
          });
        }
      })
    },
    //流程类型切换
    handleChangeProcess:function (val) {
      if(val == 0){
        this.processDialog['list'] = this.processAllData.showReclaimFlow;
        this.processDialog['checkedKeys'] = this.processRoleData.reclaimFlow.map(item => {
          return item.key
        });
      }else{
        this.processDialog['list'] = this.processAllData.showRenovationFlow;
        this.processDialog['checkedKeys'] = this.processRoleData.renovationFlow.map(item => {
          return item.key
        });
      }
    },
    //点击流程回调
    handleClickNodeProcess:function (a,b) {
      this.processDialog.checkedKeysData = b.checkedNodes;     
    },
    //提交流程
    submitProcess:function () {
      if(this.processDialog.type == 0){
        var params = {
          roleId:this.permissonData.id,
          reclaimValue:this.processDialog.checkedKeysData.map(item => {return item.key})
        };
      }else{
        var params = {
          roleId:this.permissonData.id,
          renovateId:this.processDialog.checkedKeysData.map(item => {return item.node})
        };
      };  
      this.processDialog.btnLoading = true;
      saveRoleProcessData(params).then(res => {
        this.$message.success('保存成功！');
        this.processDialog.btnLoading = false;
        this.processDialog.visible = false;       
      }).catch(() => {
        this.processDialog.btnLoading = false;
      })
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
    },
    handleSizeChange: function(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange: function(val) {
      this.handleGetTableData(val);
    }
  }
};
</script>

<style lang="scss" scoped>
.permissonList .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding: 20px;
}
.permissonList /deep/ .el-tree-node__content {
  height: 48px;
}
</style>

<style lang="scss" scoped>
.can-container {
  padding: 20px;
  background: #fff;
  .title {
    font-size: 24px;
    font-weight: 500;
    color: rgba(72, 73, 77, 1);
    line-height: 33px;
  }
}

.btnsearch {
  background: #969799;
  color: white;
}

.btnReset {
  background: white;
  color: #969799;
}
.userList {
  margin: 30px 0px;
}
.btnuser {
  border: 1px solid #2e8ae6;
  color: #2e8ae6;
}
.pages {
  text-align: center;
  margin: 20px auto;
}
.rolesTitle {
  font-size: 14px;
  color: #333333;
}
.rolesBox {
  width: 224px;
  height: 308px;
  background: #f8f8f8;
  border-radius: 4px;
  padding: 5px 15px;
}
.rolesBox p {
  padding: 5px;
  font-size: 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
}
.rolesBox p.clickNo {
  color: #2e8ae6;
  cursor: pointer;
}
.rolesBox p:hover {
  color: #2e8ae6;
  cursor: pointer;
}

.authorization {
  font-size: 16px;
  color: #333;
}
.authorizationRoles {
  color: #2e8ae6;
}

.permissonList,.processList {
  padding: 20px;
  height:50vh;
  overflow: auto;
  /deep/ .el-tree-node__label {
    font-size: 16px;
    padding: 10px 0;
  }
  /deep/ .el-tree-node__content {
    height: 40px !important;
  }
  /deep/ .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding: 20px;
  }
  /deep/ .el-tree-node__content {
    height: 48px;
  }
}
</style>
